var app = getApp();
var md5 = require("../../utils/md5.js");
var wxpay = require('../../utils/pay.js');

Page({
  data: {
    orderId: 0,
    ordernum:'',
    goodsList: [],
    yunPrice: "10.00",
    viewHidden: false,
    payArr: ["余额支付", "微信支付"],
    is_map: false,
    is_distribution: true,
    is_callqishou: true,
    statusSteps: [
      {
        current: false,
        done: false,
        text: '待支付',
        desc: ''
      },
      {
        done: false,
        current: false,
        text: '待使用',
        desc: ''
      },
      {
        done: false,
        current: false,
        text: '待评价',
        desc: ''
      },
      {
        done: false,
        current: false,
        text: '已完成',
        desc: ''
      }
    ],
    statusSteps1: [
      {
        current: false,
        done: false,
        text: '待支付',
        desc: ''
      },
      {
        done: false,
        current: false,
        text: '待接单',
        desc: ''
      },
      {
        done: false,
        current: false,
        text: '待配送',
        desc: ''
      },
      {
        done: false,
        current: false,
        text: '配送中',
        desc: ''
      },
      {
        done: false,
        current: false,
        text: '待评价',
        desc: ''
      },
      {
        done: false,
        current: false,
        text: '已完成',
        desc: ''
      }
    ],
    statusSteps2: [
      {
        current: false,
        done: true,
        text: '待支付',
        desc: ''
      },
      {
        current: false,
        done: true,
        text: '已退款',
        desc: ''
      },
      {
        current: true,
        done: true,
        text: '已取消',
        desc: ''
      },
    ],
    controls: [
      {
        id: 'sys_1',
        iconPath: '/images/nav/map.png',
        position: {
          left: 325,
          top: 60 - 30,
          width: 40,
          height: 40
        },
        clickable: true
      },
    ],
  },
  onLoad: function (e) {
    console.log(e);
  		var orderId = e.id;
      var ordernum = e.ordernum;
  		this.data.orderId = orderId;
  		this.setData({
  			orderId: orderId,
  			userTel: app.globalData.userTel,
        ordernum:ordernum,
  			orderState: wx.getStorageSync('orderState'),
  		});
      this.loadData();
  },
  loadData: function () {
    wx.showLoading({
      title: '加载中...',
    })
    var that = this;
    var open_id = app.globalData.openId + '';
    var order_id = that.data.orderId;
    var service = 'User.GetNewOrderInfo';
    var user_id = app.globalData.userId;
    var sign = md5.md5(open_id + order_id + service + user_id);
    wx.request({
      url: app.globalData.serviceUrl + 'User.GetNewOrderInfo',
      header: {
        'Content-Type': 'json'
      },
      data: {
        sign: sign,
        user_id: user_id,
        open_id: open_id,
        order_id: order_id,
      },
      success: function (res) {
        wx.hideLoading();
        var result = res.data.data;
        if (result.code == 0) {
          that.setData({
            orderDetail: result.info,
            ordernum: result.info[0].order_num
          });
          //处理地图展示
          if (result.info[0].delive_type == 2 && result.info[0].order_pid != 1) {
            console.log(result.info[0].deliveryNo);
            if (result.info[0].deliveryNo != "") {
              console.log(result.info[0]);
              console.log('配送信息');
              that.getDadaQuery(result.info[0])
            } else {
              that.setData({
                is_map: true,
                is_distribution: false,
                distribution_tel: result.info[0].order_shop_tel,
                distribution_name: '联系商家',
                distribution_service: '商家自配',
                distribution_time: '立即配送',
                distribution_address: result.info[0].delive_address
              })
            }
          } else {
            that.setData({
              is_map: true,
            })
          }
          that.updateStatusSteps(result.info);
        } else {
          wx.hideLoading();
          that.setData({
            orderList: 'null',
          });
          wx.showModal({
            title: '失败',
            content: result.msg,
            showCancel: false
          })
          return;
        }
      },
      complete: function (res) {
        console.log(res);
      },
    })
  },
  wuliuDetailsTap: function (e) {
    var orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/wuliu/index?id=" + orderId
    })
  },
  confirmBtnTap: function (e) {
    var that = this;
    var order_id = e.currentTarget.dataset.id;
    var open_id = app.globalData.openId + '';
    var user_id = app.globalData.userId;
    var service = 'Order.OrderCollect';
    var sign = md5.md5(open_id + order_id + service + user_id);
    wx.showModal({
      title: '确认您已收到商品？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading();
          wx.request({
            url: app.globalData.serviceUrl + service,
            header: {
			        'Content-Type': 'json'
			      },
            data: {
              sign: sign,
              user_id: user_id,
              open_id: open_id,
              order_id: order_id
            },
            success: function (res) {
              if (res.data.data.code == 0){
                wx.setStorageSync('orderState', 2)
                that.loadData()
                wx.hideLoading()
                wx.showModal({
                  title: '收货成功',
                  content: '收货成功前去评价吧',
                  success: function (res) {
                    if (res.confirm) {
                      wx.navigateTo({
                        url: "/pages/order-comment/index?id=" + order_id + "&shop_id=" + e.currentTarget.dataset.shop_id
                      })
                    }        
                  }
                })
              }else{
                wx.showToast({
                  title: '收货失败',
                })
                setTimeout(function () {
                  wx.navigateTo({
                    url: "/pages/order-details/index?id=" + order_id + "&ordernum=" + order_num
                  })
                }, 1000)
              }    
            }
          })
        }
      }
    })
  },
  quanxiao:function (e){
    var that = this
    var order_id = that.data.orderId
    var order_num = that.data.ordernum
    var open_id = app.globalData.openId + '';
    var user_id = app.globalData.userId;
    var service = 'Pay.Refund';
    var client = 'web'
    var sign = md5.md5(client + open_id + order_id + order_num + service + user_id);
    wx.showModal({
      title: '确认申请退款？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '退款中',
          })
          wx.request({
            url: app.globalData.serviceUrl + 'Pay.Refund',
            header: {
              'Content-Type': 'json'
            },
            data: {
              sign: sign,
              user_id: user_id,
              openid: open_id,
              order_id: order_id,
              order_num: order_num,
              client: client
            },
            success: function (res) {
              console.log(res);
              wx.hideLoading()
              if (res.data.data.code == 0) {
                wx.showToast({
                  title: '退款申请成功',
                })
                that.setData({
                  orderState: 3
                })
                that.loadData();
              } else {
                wx.showToast({
                  title: res.data.data.msg,
                  image: '/images/popup-close.png'
                })
              }
            },
            fail: function (res) {
              wx.hideLoading()
              wx.showToast({
                title: '网络错误',
              })
            }
          })
        }
      }
    })
  },
  updateStatusSteps: function (info) {
    var that = this
    if (info[0].delive_type == 2) {
      console.log(123);
      var line = info[0];
      var delive_type = line.delive_type;
      var order_pid = line.order_pid;
      var order_hexiao = line.order_hexiao;
      var pinglun = line.pinglun;
      var status = line.status;
      if (that.data.orderState === 0) {
        that.setData({
          statusSteps1: [
            {
              current: false,
              done: false,
              text: '待支付',
              desc: '等待中...'
            },
            {
              done: false,
              current: false,
              text: '待接单',
              desc: ''
            },
            {
              done: false,
              current: false,
              text: '待配送',
              desc: ''
            },
            {
              done: false,
              current: false,
              text: '配送中',
              desc: ''
            },
            {
              done: false,
              current: false,
              text: '待评价',
              desc: ''
            },
            {
              done: false,
              current: false,
              text: '已完成',
              desc: ''
            }
          ],
        })
      } else if (that.data.orderState === 1) {

        if (delive_type == 2) {
          if (status == 1) {
          
            that.setData({
              statusSteps1: [
                {
                  current: false,
                  done: true,
                  text: '待支付',
                  desc: '成功'
                },
                {
                  done: false,
                  current: false,
                  text: '待接单',
                  desc: '等待中'
                },
                {
                  done: false,
                  current: false,
                  text: '待配送',
                  desc: ''
                },
                {
                  done: false,
                  current: false,
                  text: '配送中',
                  desc: ''
                },
                {
                  done: false,
                  current: false,
                  text: '待评价',
                  desc: ''
                },
                {
                  done: false,
                  current: false,
                  text: '已完成',
                  desc: ''
                }
              ],
            })

          } else if (status == 2) {
            
            that.setData({
              statusSteps1: [
                {
                  current: false,
                  done: true,
                  text: '待支付',
                  desc: '成功'
                },
                {
                  current: false,
                  done: true,
                  text: '待接单',
                  desc: '成功'
                },
                {
                  current: false,
                  done: false,
                  text: '待配送',
                  desc: '等待中'
                },
                {
                  current: false,
                  done: false,
                  text: '配送中',
                  desc: ''
                },
                {
                  current: false,
                  done: false,
                  text: '待评价',
                  desc: ''
                },
                {
                  current: false,
                  done: false,
                  text: '已完成',
                  desc: ''
                }
              ],
            })

          } else if (status == 3) {
            that.setData({
              statusSteps1: [
                {
                  current: false,
                  done: true,
                  text: '待支付',
                  desc: '成功'
                },
                {
                  done: true,
                  current: false,
                  text: '待接单',
                  desc: '成功'
                },
                {
                  done: true,
                  current: false,
                  text: '待配送',
                  desc: '成功'
                },
                {
                  done: true,
                  current: true,
                  text: '配送中',
                  desc: '成功'
                },
                {
                  done: false,
                  current: false,
                  text: '待评价',
                  desc: ''
                },
                {
                  done: false,
                  current: false,
                  text: '已完成',
                  desc: ''
                }
              ],
            })
          }
        }

      } else if (that.data.orderState === 2) {
        that.setData({
          statusSteps1: [
            {
              current: false,
              done: true,
              text: '待支付',
              desc: '成功'
            },
            {
              done: true,
              current: false,
              text: '待接单',
              desc: '成功'
            },
            {
              done: true,
              current: false,
              text: '待配送',
              desc: '成功'
            },
            {
              done: true,
              current: false,
              text: '配送中',
              desc: '成功'
            },
            {
              done: false,
              current: true,
              text: '待评价',
              desc: '待确认'
            },
            {
              done: false,
              current: false,
              text: '已完成',
              desc: ''
            }
          ],
        })

      } else if (that.data.orderState === 3) {
        if (status != 5) {
        that.setData({
          statusSteps1: [
            {
              current: false,
              done: true,
              text: '待支付',
              desc: ''
            },
            {
              current: false,
              done: true,
              text: '待接单',
              desc: ''
            },
            {
              current: false,
              done: true,
              text: '待配送',
              desc: ''
            },
            {
              current: false,
              done: true,
              text: '配送中',
              desc: ''
            },
            {
              current: false,
              done: true,
              text: '待评价',
              desc: ''
            },
            {
              current: true,
              done: true,
              text: '已完成',
              desc: ''
            }
          ],
        })
        } else {
          that.setData({
            statusSteps1: [
              {
                current: false,
                done: true,
                text: '待支付',
                desc: ''
              },
              {
                current: false,
                done: true,
                text: '待接单',
                desc: ''
              },
              {
                current: false,
                done: true,
                text: '待配送',
                desc: ''
              },
              {
                current: false,
                done: true,
                text: '配送中',
                desc: ''
              },
              {
                current: false,
                done: true,
                text: '待评价',
                desc: ''
              },
              {
                current: true,
                done: true,
                text: '已完成',
                desc: ''
              }
            ],
          })
        }

      }
    } else {
      console.log(456);      
      if (that.data.orderState === 0) {
        that.setData({
          statusSteps: [
            {
              current: true,
              done: false,
              text: '待支付',
              desc: '等待中...'
            },
            {
              current: false,
              done: false,
              text: '待使用',
              desc: ''
            },
            {
              current: false,
              done: false,
              text: '待评价',
              desc: ''
            },
            {
              current: false,
              done: false,
              text: '已完成',
              desc: ''
            }
          ]
        })
      } else if (that.data.orderState === 1) {
        that.setData({
          statusSteps: [
            {
              current: false,
              done: true,
              text: '待支付',
              desc: '成功'
            },
            {
              current: true,
              done: false,
              text: '待使用',
              desc: '等待中...'
            },
            {
              current: false,
              done: false,
              text: '待评价',
              desc: ''
            },
            {
              current: false,
              done: false,
              text: '已完成',
              desc: ''
            }
          ]
        })
      } else if (that.data.orderState === 2) {
        that.setData({
          statusSteps: [
            {
              current: false,
              done: true,
              text: '待支付',
              desc: '成功'
            },
            {
              current: false,
              done: true,
              text: '待使用',
              desc: '成功'
            },
            {
              current: true,
              done: false,
              text: '待评价',
              desc: '等待中...'
            },
            {
              current: false,
              done: false,
              text: '已完成',
              desc: ''
            }
          ]
        })
      } else if (that.data.orderState === 3) {
        if (status != 5) {
          that.setData({
            statusSteps: [
              {
                current: false,
                done: true,
                text: '待支付',
                desc: '成功'
              },
              {
                current: false,
                done: true,
                text: '待使用',
                desc: '成功'
              },
              {
                current: false,
                done: true,
                text: '待评价',
                desc: '成功'
              },
              {
                current: true,
                done: true,
                text: '已完成',
                desc: ''
              }
            ]
          })
        } 
      }
    }
  },

  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    if (e.detail.value == 0) {
      this.toPayCredit(e);
    } else {
      this.toPayTap(e);
    }
  },
  toPayTap: function (e) {
    wx.showToast({
      title: '微信支付中',
      icon: 'loading'
    })
    var that = this;
    var client = 'wxa';
    var cost = e.currentTarget.dataset.money;
    var openid = app.globalData.openId;
    var order_id = e.currentTarget.dataset.id;
    var order_num = e.currentTarget.dataset.number;
    var service = 'Pay.Index';
    var type = 'wechat';
    var user_id = app.globalData.userId;
    var sign = md5.md5(client + cost + openid + order_id + order_num + service + type + user_id);
    wx.request({
      url: app.globalData.serviceUrl + 'Pay.Index',
      header: {
        'Content-Type': 'json'
      },
      data: {
        client: client,
        cost: cost,
        openid: openid,
        order_id: order_id,
        order_num: order_num,
        type: type,
        user_id: user_id,
        sign: sign,
      },
      success: function (res) {
        wx.hideToast()
        var result = res.data.data;
        if (result.code != 0) {
          wx.showModal({
            title: '失败',
            content: result.msg,
            showCancel: false
          })
          return;
        }
        wxpay.wxpay(app, cost, order_num, "/pages/ucenter/order-list/index", 'product', order_id, md5);
      },
      complete: function (res) {
        wx.hideToast()
        console.log(res);
      },
    })
  },
  toPayCredit: function (e) {
    wx.showToast({
      title: '余额支付中',
      icon: 'loading'
    })
    var that = this;
    var client = 'wxa';
    var cost = e.currentTarget.dataset.money;
    var openid = app.globalData.openId;
    var order_id = e.currentTarget.dataset.id;
    var order_num = e.currentTarget.dataset.number;
    var service = 'Pay.Index';
    var type = 'credit';
    var user_id = app.globalData.userId;
    var sign = md5.md5(client + cost + openid + order_id + order_num + service + type + user_id);
    wx.request({
      url: app.globalData.serviceUrl + 'Pay.Index',
      header: {
        'Content-Type': 'json'
      },
      data: {
        client: client,
        cost: cost,
        openid: openid,
        order_id: order_id,
        order_num: order_num,
        type: type,
        user_id: user_id,
        sign: sign,
      },
      success: function (res) {
        wx.hideToast();
        var result = res.data.data;
        if (result.code != 0) {
          wx.showModal({
            title: '失败',
            content: result.msg,
            showCancel: false
          })
        } else {
          wx.showModal({
            title: '成功',
            content: result.msg,
            showCancel: false
          })
          wx.setStorageSync('orderState', 1)
          that.setData({
            orderState: wx.getStorageSync('orderState'),
          });
          that.loadData();
        }
      },
      complete: function (res) {
        wx.hideToast()
        console.log(res);
      },
    })
  },


  //拨打商家电话
  callPhone: function () {
    var that = this
    var phone = that.data.orderDetail[0].order_shop_tel
    wx.makePhoneCall({
      phoneNumber: phone,
      success: function () {
        console.log("成功拨打电话")
      },
    })
  },

  //拨打配送员电话
  callPhoneDistribution: function () {
    var that = this
    var phone = that.data.distribution_tel
    wx.makePhoneCall({
      phoneNumber: phone,
      success: function () {
        console.log("成功拨打电话")
      },
    })
  },

  //重置地图
  controltap: function (e) {
    this.setData({
      latitude: this.data.latitude,
      longitude: this.data.longitude,
    })
    console.log(this.data);
    console.log('地图重置');
  },

  //用于获取配送信息查询
  getDadaQuery: function (info) {
    var that = this;
    var service = 'Dada.Query'
    var order_id = info.order_num
    var delive_address = info.delive_address
    var jingwei = info.delive_jingwei.split(",")
    var shop_jingwei = info.shop_address_jingwei.split(",")
    var lat = jingwei[0];
    var lng = jingwei[1];
    var shop_lat = shop_jingwei[0];
    var shop_lng = shop_jingwei[1];
    var sign = md5.md5(order_id + service);
    wx.request({
      url: app.globalData.serviceUrl + service,
      header: {
        'Content-Type': 'json'
      },
      data: {
        sign: sign,
        order_id: order_id,
      },
      success: function (res) {
        console.log(res);
        var result = res.data.data;
        if (result.code == 0) {
          that.setData({
            height: '300px',
            is_map: false,
            is_distribution: false,
            is_callqishou: false,
            distribution_tel: result.info.supplierPhone,
            distribution_name: '联系骑手',
            distribution_service: '达达配送',
            distribution_time: '立即配送',
            distribution_address: delive_address,
            latitude: lat,
            longitude: lng,
            markers: [{
              id: 1,
              latitude: lat,
              longitude: lng,

            },
            {
              id: 2,
              latitude: result.info.supplierLat,
              longitude: result.info.supplierLng,
              iconPath: '/images/nav/qis.png',
              width: 20,
              height: 20,
              label: {
                content: result.info.statusMsg,
                fontSize: 13,
                color: '#e62a39',
                anchorX: 1,
                anchorY: 5,
                bgColor: '#ffffff',
                textAlign: 'center',
                padding: 4,
                borderRadius: 6,
                borderWidth: 1,
                borderColor: "#e62a39",
                display: 'ALWAYS',
              },
            },
            {
              id: 3,
              latitude: shop_lat,
              longitude: shop_lng,
              iconPath: '/images/nav/shop2.png',
              width: 20,
              height: 20,
            }
            ],
          })
        } else {
          that.setData({
            height: '300px',
            is_map: false,
            is_distribution: false,
            distribution_tel: info.order_shop_tel,
            distribution_name: '联系商家',
            distribution_service: '达达配送',
            distribution_time: '立即配送',
            distribution_address: delive_address,
            latitude: lat,
            longitude: lng,
            markers: [{
              id: 1,
              latitude: lat,
              longitude: lng,
            },
            {
              id: 2,
              latitude: shop_lat,
              longitude: shop_lng,
              iconPath: '/images/nav/shop2.png',
              width: 20,
              height: 20,
              label: {
                content: '待接单',
                fontSize: 13,
                color: '#e62a39',
                anchorX: 1,
                anchorY: 5,
                bgColor: '#ffffff',
                textAlign: 'center',
                padding: 4,
                borderRadius: 6,
                borderWidth: 1,
                borderColor: "#e62a39",
                display: 'ALWAYS',
              },
            }
            ],
          })
        }
        that.controltap();
      },
      complete: function (res) {
        console.log(res);
      },
      fail: function () {
        //请求超时提示
        wx.showModal({
          title: '提示',
          content: '网络超时',
          showCancel: false
        })
        return;
      }
    })
  },
})